package com.yj.smarthome.test.ipcamera;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class HttpRequestComponment implements IHttpRequestService {

	String defaultContentEncoding;

	IPCamera camera;

	public HttpRequestComponment(IPCamera camera) {
		this.camera = camera;
		System.out.println(this.camera);
	}

	/**
	 * send http request
	 * 
	 * @param urlString
	 * @param method
	 *            : POST/GET
	 * @param parameters
	 * @param propertys
	 * @return
	 * @throws IOException
	 */
	private HttpResponse send(String urlString, String method, Map<String, String> parameters, Map<String, String> propertys)
			throws IOException {
		HttpURLConnection urlConnection = null;

		if (method.equalsIgnoreCase("GET") && parameters != null) {
			StringBuffer param = new StringBuffer();
			int i = 0;
			for (String key : parameters.keySet()) {
				if (i == 0)
					param.append("?");
				else
					param.append("&");
				param.append(key).append("=").append(parameters.get(key));
				i++;
			}
			urlString += param;
		}
		URL url = new URL(urlString);
		urlConnection = (HttpURLConnection) url.openConnection();
		urlConnection.setConnectTimeout(15000);
		urlConnection.setReadTimeout(15000);

		urlConnection.setRequestMethod(method);
		urlConnection.setDoOutput(true);
		urlConnection.setDoInput(true);
		urlConnection.setUseCaches(false);

		if (propertys != null)
			for (String key : propertys.keySet()) {
				urlConnection.addRequestProperty(key, propertys.get(key));
			}

		if (method.equalsIgnoreCase("POST") && parameters != null) {
			StringBuffer param = new StringBuffer();
			for (String key : parameters.keySet()) {
				param.append("&");
				param.append(key).append("=").append(parameters.get(key));
			}
			urlConnection.getOutputStream().write(param.toString().getBytes());
			urlConnection.getOutputStream().flush();
			urlConnection.getOutputStream().close();
		}
		return this.makeContent(urlString, urlConnection);
	}

	/**
	 * get response object
	 * 
	 * @param urlString
	 * @param urlConnection
	 * @return
	 * @throws IOException
	 */
	private HttpResponse makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
		HttpResponse httpResponser = new HttpResponse();
		try {
			InputStream in = urlConnection.getInputStream();
			byte[] buffer = new byte[1024];
			int len = -1;
			int left = 0;
			ByteBuffer bb = null;
			//end
			byte[] end = { 13, 10, 13, 10 };
			//54 
			//--ipcamera
			//Content-Type: image/jpeg
			//Content-Length: 
			byte[] seperator = { 45, 45, 105, 112, 99, 97, 109, 101, 114, 97, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112,
					101, 58, 32, 105, 109, 97, 103, 101, 47, 106, 112, 101, 103, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 76, 101,
					110, 103, 116, 104, 58, 32 };
			int slen = seperator.length;
			byte[] map = { 45, 45, 105, 112, 99, 97, 109, 101, 114, 97 };
			int count = 0;
			boolean canreads = false;
			while ((len = in.read(buffer)) != -1) {
				try {
					if (left <= 0) {
						if (bb != null) {
//					    	   saveImage(bb, "e:/"+count+".jpg");
//					    	   count++;
//					    	   bb = null;
							camera.setImage(bb);
						}
						if (buffer[0] == 45 && buffer[1] == 45) {
							canreads = true;
							System.out.println("a new image!" + 0 + "\t\t" + new String(buffer, 0, 10));
							if (buffer[53] == 32) {
								char[] c = new char[10];
								int clen = 0;
								for (int i = 54; i < 54 + 10; i++) {
									if (buffer[i] == 13 && buffer[i + 1] == 10)
										break;
									c[i - 54] = (char) buffer[i];
									clen++;
								}
								String maplen = new String(c, 0, clen);
								left = Integer.parseInt(maplen);
								bb = ByteBuffer.allocate(left + 2);
								System.out.println("***********************eading length!" + maplen);
								int offset = 58 + clen;
								bb.put(buffer, 54 + clen + end.length, len - offset);
								left -= (len - offset);
							}
						}
					} else {
						if (canreads) {
							bb.put(buffer, 0, len);
							left -= len;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					canreads = false;
					left = 0;
					bb = null;
					continue;
				}
			}

//			   System.out.println("capacity:"+bb.capacity());
//			   System.out.println("position:"+bb.position());
//			   System.out.println("limit:"+bb.limit());
//			   System.out.println("remaining:"+bb.remaining());
//			   System.out.println("len:"+len);
//			   System.out.println("left:"+left);

			return httpResponser;
		} catch (IOException e) {
			throw e;
		} finally {
			if (urlConnection != null)
				urlConnection.disconnect();
		}
	}

	public void saveImage(ByteBuffer bb, String filename) throws ImageFormatException, IOException {
		ByteArrayInputStream bais = new ByteArrayInputStream(bb.array());
		JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(bais);
//	    BufferedImage image = decoder.decodeAsBufferedImage();
//	    BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(new File(filename)));
//	    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bf);
//	    encoder.encode(image);
//	    bf.flush();
//	    bf.close();
	}

	public HttpResponse sendGet(String urlString) throws IOException {
		// TODO Auto-generated method stub
		return send(urlString, "GET", null, null);
	}

	public HttpResponse sendGet(String urlString, Map<String, String> params) throws IOException {
		// TODO Auto-generated method stub
		return send(urlString, "GET", params, null);
	}

	public HttpResponse sendGet(String urlString, Map<String, String> params, Map<String, String> propertys) throws IOException {
		// TODO Auto-generated method stub
		return send(urlString, "GET", params, propertys);
	}

	public HttpResponse sendPost(String urlString) throws IOException {
		// TODO Auto-generated method stub
		return send(urlString, "POST", null, null);
	}

	public HttpResponse sendPost(String urlString, Map<String, String> params) throws IOException {
		// TODO Auto-generated method stub
		return send(urlString, "POST", params, null);
	}

	public HttpResponse sendPost(String urlString, Map<String, String> params, Map<String, String> propertys) throws IOException {
		// TODO Auto-generated method stub
		return send(urlString, "POST", params, propertys);
	}

	/**
	 * set content enconding
	 */
	public void setDefaltContentEncoding(String defaultContentEncoding) {
		// TODO Auto-generated method stub
		this.defaultContentEncoding = defaultContentEncoding;
	}

	public static void main(String args[]) {
//		String url = "http://192.168.0.178/snapshot.cgi?user=admin&pwd=123456";
//		String url = "http://192.168.0.178/videostream.cgi?user=admin&pwd=123456&resolution=320*240&rate=14";
		String url = "http://192.168.1.158/cgi-bin/hi3510/param.cgi?cmd=getvideoattr";
		Map<String, String> params = new HashMap<String, String>();
		HttpRequestComponment hrc = new HttpRequestComponment(null);
		hrc.setDefaltContentEncoding("utf-8");
		try {
			HttpResponse response = hrc.sendPost(url, params);
//			System.out.println(response.content);
			System.out.println(response);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
